package cn.yitun.chat.yitunserverimcore.general.main.biz.chat.manager;

import cn.yitun.chat.yituncommonmessage.ExceptionEnum;
import cn.yitun.chat.yituncommonmessage.YitunException;
import cn.yitun.chat.yituncommonutil.YitunCollectionUtil;
import cn.yitun.chat.yituncommonutil.YitunStringUtil;
import cn.yitun.chat.yitunservercommonlib.converter.dto2vo.user.UserLastChatDto2VoConverter;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.base.chat.ChatItem;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.group.GroupChatContentDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.group.GroupChatItemDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.userchat.LastChatDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.po.group.GroupInfo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.group.GroupChatItemVo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.group.GroupMemberVo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.system.user.UserVo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.userchat.LastChatVo;
import cn.yitun.chat.yitunservercommonlib.enums.userChat.UserChatTypeEnums;
import cn.yitun.chat.yitunservercommonlib.util.NumUtil;
import cn.yitun.chat.yitunservercommonlib.util.codec.IdGen;
import cn.yitun.chat.yitunserverimbase.dao.group.GroupChatContentDao;
import cn.yitun.chat.yitunserverimbase.dao.group.GroupChatItemDao;
import cn.yitun.chat.yitunserverimbase.dao.group.GroupDao;
import cn.yitun.chat.yitunserverimbase.dao.group.GroupMemberDao;
import cn.yitun.chat.yitunserverimbase.dao.userchat.LastChatDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * Date 2019-02-17 12:24:49<br>
 * Description
 * 
 * @author yitun<br>
 * @version 1.1
 */
@Service
public class GroupChatManager {

	@Resource
	private GroupChatContentDao groupChatDAO;
	@Resource
	private GroupChatItemDao groupChatItemDao;
	@Resource
	private LastChatDao userLastChatDAO;
	@Resource
	private GroupDao groupDao;
	@Resource
	private GroupMemberDao groupMemberDao;

	/**
	 * 添加群聊历史记录
	 */
	@Transactional
	public void addGroupChatHistory(
			UserVo userData,
			Long messageId,
			Long groupId,
			List<ChatItem> chatItemList) {
		messageId = NumUtil.isInValid(messageId) ? IdGen.getNumber() : messageId;

		List<Long> messageKeys = new ArrayList<>();
		messageKeys.add(messageId);
		List<GroupChatItemVo> hasList = groupChatItemDao.getGroupChatItemListByMessageIds(messageKeys);
		if (YitunCollectionUtil.isNotEmpty(hasList)) {
			return;
		}

		Long userId = userData.getId();
		Long contentId = 0l;
		GroupChatContentDto content = createGroupChatContent(messageId, groupId, userData);
		groupChatDAO.save(content);
		List<GroupChatItemDto> list = new ArrayList<>();
		for (ChatItem item : chatItemList) {
			if (YitunStringUtil.isEmpty(item.getValue()))
				continue;

			GroupChatItemDto chatLog = new GroupChatItemDto();
			chatLog.setMessageId(messageId);
			chatLog.setGroupChatContentId(content.getId());
			chatLog.setGroupId(content.getGroupId());
			chatLog.setUserId(content.getUserId());
			chatLog.setRank(item.getRank());
			chatLog.setSection(item.getSection());
			chatLog.setType(item.getType());
			chatLog.setValue(item.getValue());
			chatLog.setFilterValue(item.getFilterValue());
			chatLog.setCreateBy(content.getUserId());
			chatLog.setUpdateBy(content.getUserId());
			list.add(chatLog);
		}
		if (YitunCollectionUtil.isNotEmpty(list))
			groupChatItemDao.saveList(list);

		contentId = content.getId();

		LastChatDto userLastChat = createUserLastChat(messageId, contentId, userId, groupId, UserChatTypeEnums.TYPE_GROUP.getType());
		saveOrUpdateLast(userLastChat);
	}

	/**
	 * 创建群聊天记录
	 * @param messageKey
	 * @param groupId
	 * @param userData
	 * @return
	 */
	private GroupChatContentDto createGroupChatContent(Long messageKey, Long groupId, UserVo userData) {
		GroupInfo group = groupDao.get(groupId);
		if (group == null)
			throw new YitunException(ExceptionEnum.BUSY_SERVER);

		GroupChatContentDto chatLog = new GroupChatContentDto();

		chatLog.setMessageId(messageKey);
		chatLog.setGroupId(groupId);
		chatLog.setGroupName(group.getName());
		chatLog.setGroupHead(group.getHead());
		chatLog.setGroupAvatar(group.getAvatar());
		chatLog.setUserHead(userData.getHead());
		chatLog.setUserAvatar(userData.getAvatar());
		chatLog.setUserId(userData.getId());
		chatLog.setUserName(userData.getName());
		chatLog.setCreateBy(userData.getId());
		chatLog.setUpdateBy(userData.getId());
		// 获取群成员详情
		GroupMemberVo gm = groupMemberDao.getVOByGroupIdUserId(groupId, userData.getId());
		if (gm == null)
			throw new YitunException(ExceptionEnum.BUSY_SERVER);

		chatLog.setUserPosition(gm.getPosition());
		chatLog.setUserNickname(userData.getNickname());
		chatLog.setUserGroupNickname(userData.getNickname());
		return chatLog;
	}

	private void saveOrUpdateLast(LastChatDto userLastChat) {
		saveOrUpdate(userLastChat);
	}

	/**
	 * 最后聊天条目
	 * @param messageKey
	 * @param contentId
	 * @param userId
	 * @param chatId
	 * @param type
	 * @return
	 */
	private LastChatDto createUserLastChat(Long messageKey, Long contentId, Long userId, Long chatId, String type) {

		long timestamp = System.currentTimeMillis();
		LastChatDto bean = new LastChatDto();
		bean.setChatId(chatId);
		bean.setContentId(contentId);
		bean.setMessageId(messageKey);
		bean.setType(type);
		bean.setUserId(userId);
		return bean;
	}

	/**
	 * 保存最后用户最后聊天记录
	 * @param userLastChat
	 */
	public void saveOrUpdate(LastChatDto userLastChat) {
		LastChatVo userLastChatVo = userLastChatDAO.getLastChat(userLastChat.getUserId(), userLastChat.getChatId(), userLastChat.getType());
		if (null != userLastChatVo) {
			long timestamp = System.currentTimeMillis();
			userLastChatVo.setMessageId(userLastChat.getMessageId());
			userLastChatVo.setContentId(userLastChat.getContentId());
			userLastChatDAO.update(UserLastChatDto2VoConverter.INSTANCE.vo2dto(userLastChatVo));
		} else {
			userLastChatDAO.save(userLastChat);
		}
	}
}
